<?php

namespace Haozing\FastCore\Helper;

use Haozing\FastCore\Context\UserContext;
use Hyperf\Context\ApplicationContext;
use Psr\Http\Message\ServerRequestInterface;

class Tenant
{
    public static function dataHandle(array $data): array
    {
        //先判断$data中是否设置过，如果设置过，则不设置
        if (!empty($data['tenant_id'])) {
            return $data;
        }
        //如果是登录用户中存在，则用登录用的
        $authUser = UserContext::get();
        $tenantId = $authUser->get('tenant_id');
        if (empty($tenantId)) {
            //否则从请求头$request获取租户tid
            $tenantId = ApplicationContext::getContainer()->get(ServerRequestInterface::class)->getAttribute('tid',-1);
        }

        if ($tenantId) {
            $data['tenant_id'] = $tenantId;
        }
        return $data;
    }
}